package com.gougou.controller;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.gougou.pojo.TbUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车处理器
 * Created by EX-ZHANZHENQIANG001 on 2018-04-26.
 */
@RequestMapping("/shoopingCart")
@Controller
public class ShoppingCartController {

    /**
     * cookie key
     */
    private static final String SHOOPING_CART = "shooping_cart";

    private static final String GOGOU_USER_SESSION = "gogou_user_session";

    /**
     * 添加商品至购物车
     * @param request
     * @param response
     */
    @RequestMapping("/addCommodityInit")
    public String addCommodityInit(HttpServletRequest request, HttpServletResponse response) {
        return "/addCommodity";
    }

    /**
     * 添加商品至购物车
     * @param request
     * @param response
     */
    @RequestMapping("/addCommodity")
    @ResponseBody
    public ModelAndView addCommodity(HttpServletRequest request, HttpServletResponse response,
                                     @RequestParam Map<String, String> commodityMap) {
        Map paramMap = request.getParameterMap();
        //当前购物车所属cookie
        Cookie currentCookie = null;
        //购物车集合
        List<Map> commodityList = null;
        //创建json对象转转换映射类
        ObjectMapper objectMapper = new ObjectMapper();
        //从用户cookie中获取商品信息
        Cookie[] cookies = request.getCookies();
        //用户是否已经创建了cookie购物车，如果没有创建则创建一个，如果创建了则直接从cookie中取
        for (Cookie cookie : cookies) {
            //判断cookie对象是否有购物车对象
            if(StringUtils.equals(SHOOPING_CART, cookie.getName())) {
                currentCookie = cookie;
                break;
            }
        }
        //不管有没有商品列表，都需要计算总价
        commodityMap.put("priceCount", priceCount(commodityMap.get("count"), commodityMap.get("price")));
        if(null == currentCookie) {
            commodityList = new ArrayList<Map>();
            commodityList.add(commodityMap);
        } else {
            try {
                //将新的商品类目放入cookie购物车中，首先需要从cookie中取出商品集合信息
                String jsonValue = URLDecoder.decode(currentCookie.getValue(), "UTF-8");
                //将当前json转换为对象
                commodityList = objectMapper.readValue(jsonValue, List.class);
                boolean isAddCommodity = true;
                //处理商品类目的添加
                for (Map<String, String> map : commodityList) {
                    //如果购物车中已经有相同的商品条目，则将数量相加
                    if(map.containsValue(commodityMap.get("cid"))) {
                        map.put("count", add(map.get("count"), commodityMap.get("count")));
                        //重新计算商品总价
                        map.put("priceCount", priceCount(map.get("count"), map.get("price")));
                        isAddCommodity = false;
                        break;
                    }
                }
                if(isAddCommodity) {
                    //将商品类目添加到集合中
                    commodityList.add(commodityMap);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            //类型转换
            String jsonValue = objectMapper.writeValueAsString(commodityList);
            System.out.println(jsonValue);
            //新建购物车对象集合并存放到cookie中
            Cookie ck = new Cookie(SHOOPING_CART, URLEncoder.encode(jsonValue, "UTF-8"));
            //将新增的cookie添加到返回中
            response.addCookie(ck);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //判断用户是否已经登录了，如果登陆了，则将购物车存放在redis中
        HttpSession httpSession = request.getSession();
        Object userSession = httpSession.getAttribute(GOGOU_USER_SESSION);
        if(userSession != null) {
            //将商品信息保存在当前用户的redis中
            TbUser tbUser = userSession instanceof TbUser ? (TbUser) userSession : new TbUser();
            //获取用户ID，如果获取为空则不执行操作
            if(!StringUtils.isEmpty(String.valueOf(tbUser.getId()))) {
                //通过redis将用户的新的商品条目放入到购物车列表中
                //获取用户的购物车列表，判断是否有相同的物品条目，如果有相同的物品条目，则将增加商品数据

                //没有该商品条目，则新增该商品条目

            }
        }
        //如果用户登陆，将cookie的过期时间设置为-1，立马过期

        //否则将用户的cookie过期时间设置为24小时过期

        //将商品条目信息返回
        ModelAndView modelAndView = new ModelAndView("/cart");
        modelAndView.addObject("commodityList", commodityList);
        return modelAndView;
    }



    private static String add(String num1, String num2) {
        return String.valueOf(Integer.valueOf(num1) + Integer.valueOf(num2));
    }


    private static String priceCount(String num1, String num2) {
        return String.valueOf(Integer.valueOf(num1) * Integer.valueOf(num2));
    }

}
